package com.gzc.just.play.last.war.common.message;

import com.gzc.just.play.last.war.common.message.handler.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Message dispatcher
 * Responsible for dispatching messages to specific handlers
 */
@Component
public class MessageDispatcher {

    private static final Logger log = LoggerFactory.getLogger(MessageDispatcher.class);

    private final PlayerMoveHandler playerMoveHandler;
    private final PlayerAttackHandler playerAttackHandler;
    private final SkillUseHandler skillUseHandler;
    private final ItemUseHandler itemUseHandler;
    private final ChatMessageHandler chatMessageHandler;
    private final BattleHandler battleHandler;
    private final QuestHandler questHandler;
    
    public MessageDispatcher(
            PlayerMoveHandler playerMoveHandler,
            PlayerAttackHandler playerAttackHandler,
            SkillUseHandler skillUseHandler,
            ItemUseHandler itemUseHandler,
            ChatMessageHandler chatMessageHandler,
            BattleHandler battleHandler,
            QuestHandler questHandler) {
        this.playerMoveHandler = playerMoveHandler;
        this.playerAttackHandler = playerAttackHandler;
        this.skillUseHandler = skillUseHandler;
        this.itemUseHandler = itemUseHandler;
        this.chatMessageHandler = chatMessageHandler;
        this.battleHandler = battleHandler;
        this.questHandler = questHandler;
    }
    
    private final Map<String, MessageHandlerInterface> handlerMap = new HashMap<>();

    /**
     * Initialize handler mapping
     */
    private void initHandlerMap() {
        if (handlerMap.isEmpty()) {
            handlerMap.put("PLAYER_MOVE", playerMoveHandler);
            handlerMap.put("PLAYER_ATTACK", playerAttackHandler);
            handlerMap.put("USE_SKILL", skillUseHandler);
            handlerMap.put("USE_ITEM", itemUseHandler);
            handlerMap.put("CHAT_MESSAGE", chatMessageHandler);
            handlerMap.put("BATTLE_JOIN", battleHandler);
            handlerMap.put("BATTLE_LEAVE", battleHandler);
            handlerMap.put("BATTLE_ACTION", battleHandler);
            handlerMap.put("QUEST_ACCEPT", questHandler);
            handlerMap.put("QUEST_COMPLETE", questHandler);
        }
    }

    /**
     * Dispatch message
     */
    public void dispatch(Long playerId, String messageType, Object messageData) {
        initHandlerMap();
        
        MessageHandlerInterface handler = handlerMap.get(messageType);
        if (handler != null) {
            try {
                handler.handle(playerId, messageData);
            } catch (Exception e) {
                log.error("Error handling message type: {} for player: {}", messageType, playerId, e);
            }
        } else {
            log.warn("No handler found for message type: {}", messageType);
        }
    }
}
